package shopping.worker;

import com.jd.platform.async.callback.ICallback;
import com.jd.platform.async.callback.IWorker;
import com.jd.platform.async.worker.WorkResult;
import com.jd.platform.async.wrapper.WorkerWrapper;
import shopping.ServiceRpc;
import shopping.mode.Produce;
import shopping.mode.TempOrder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 产品校验
 * 1、校验校验
 */
public class ProduceWorker implements IWorker<TempOrder,Map<String,Object>> , ICallback<TempOrder,Map<String,Object>> {


    /**
     * 第一个被调用
     */
    @Override
    public void begin() {
        //ICallback.super.begin();
        /**
         * @TODO 初始化参数
         * 比如初始化需要得service服务对象
         */
        System.err.println("产品校验开始----------");
    }

    /**
     * 核心处理点
     * @param object      object  传入参数
     * @param allWrappers 任务包装  其他线程包裹对象
     * @return
     */
    @Override
    public Map<String,Object> action(TempOrder object, Map<String, WorkerWrapper> allWrappers) {
        // WorkerWrapper workerWrapper = allWrappers.get("one");  可以通过该对象获取其他得线程对象
        /**
         * 1、接收参数
         * 2、对象参数
         * 3、校验产品
         */
        Map<String,Object> result = new HashMap<>();
        List<Produce> ps = object.getProduces();
        for(Produce p : ps) {
            Map<String,Object> rs = ServiceRpc.checkProduce(p);
            result.put(p.getProdNo(),rs);
        }
        result.put("success",true);
        result.put("msg","产品校验完成");
        return result;
    }

    @Override
    public Map<String,Object> defaultValue() {

        Map<String,Object> defaultResult = new HashMap<>();
        defaultResult.put("success",false);
        defaultResult.put("msg","校验产品异常，请联系管理员！");
        return defaultResult;
    }

    @Override
    public void result(boolean success, TempOrder tempOrder, WorkResult<Map<String,Object>> workResult) {
        Map<String,Object> result = (Map<String,Object>)workResult.getResult();
        if ((boolean)result.get("success")) {
            Set<String> pSet = result.keySet();
            for(String k : pSet) {
                if(k != "success" && k != "msg") {
                    Map<String,Object> rs = (Map<String, Object>) result.get(k);
                    boolean suFlag = (boolean)rs.get("success");
                    String msg = (String)rs.get("msg");
                    System.err.println("产品校验结束----------：" + suFlag + ",msg:" + msg);
                }
            }
        } else {
            boolean suFlag = (boolean)result.get("success");
            String msg = (String)result.get("msg");
            System.err.println("产品校验结束----------：" + suFlag + ",msg:" + msg);
        }

    }

}
